import { forwardRef, useImperativeHandle, useRef } from "react";
import "./App.css";



// 如下组件实现了点击评论按钮，跳转到底部的功能
let comments = []
for (let i = 0; i < 50; i++) {
    comments.push(`comments #${i}`)
}
const CommentC = forwardRef((props, ref) => {
    const divRef = useRef(null)
    // 不暴露整个input标签，仅仅暴露里面的focus方法和scrollIntoView方法
    useImperativeHandle(ref, () => {
        return {
            scrollToBottom() {
                const node = divRef.current
                node.scrollTop = node.scrollHeight
            }
        }
    }, [])
    return <div className="CommentList" ref={divRef}>
            {comments.map((item, index) => {
                return <p key={index}>{item}</p>
            })}
        </div>
}) 

const InputC = forwardRef((props, ref) => {
    return <input ref={ref} placeholder="请输入ref" />
})
function Post (props, ref) {
    const commentsRef = useRef(null)
    const addCommentRef = useRef(null)
    useImperativeHandle(ref, () => {
        return {
            scrollAndFocusAddComment() {
                addCommentRef.current.focus()
                commentsRef.current.scrollToBottom()
            }
        }
    }, [])
    return <>
        <article>
            <p>welcome to my blog</p>
        </article>
        <CommentC ref={commentsRef}></CommentC>
        <InputC ref={addCommentRef}></InputC>
    </>
}
const PostC = forwardRef(Post)

function App() {
    const postRef = useRef(null)
    return (
        <>
        <button onClick={(e) => {postRef.current.scrollAndFocusAddComment()}}>write a comment</button>
        <div className="card">
            <PostC ref={postRef}></PostC>
        </div>
        </>
    );
}

export default App;
